package com.liyuan.help_e.service.impl;

import com.liyuan.help_e.component.EnumUtils;
import com.liyuan.help_e.dao.ReplyDao;
import com.liyuan.help_e.model.Comment;
import com.liyuan.help_e.model.GeneralReply;
import com.liyuan.help_e.model.Reply;
import com.liyuan.help_e.model.User;
import com.liyuan.help_e.service.CommentService;
import com.liyuan.help_e.service.QuestionService;
import com.liyuan.help_e.service.ReplyService;
import com.liyuan.help_e.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    UserService userService;
    @Autowired
    ReplyDao replyDao;
    @Autowired
    QuestionService questionService;
    @Autowired
    CommentService commentService;
    @Override
    public <T> List<GeneralReply> dealReplies() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user =userService.selectUserByUsername(username);
        List<Reply> replies = replyDao.selectRepliesByReceiverId(user.getId());
        List<GeneralReply> generalReplyList =new ArrayList<>();
        for(Reply reply:replies){
            Comment comment = commentService.selectCommentById(reply.getCommentId());
            if(reply.getType()== EnumUtils.REPLY_QUESTION.getType()){
                T commentedQuestion = (T) questionService.selectQuestionById(reply.getTargetId());
                generalReplyList.add(new GeneralReply(reply.getId(),comment,commentedQuestion,reply.getStatus()));
            }else {
                T commentedComment = (T) commentService.selectCommentById(reply.getTargetId());
                generalReplyList.add(new GeneralReply(reply.getId(),comment,commentedComment,reply.getStatus()));
            }
        }
        return generalReplyList;
    }

    private void completeUserInfo(User userReceiver, User userReceiver2) {
        userReceiver2.setRole(userReceiver.getRole().getId());
        userReceiver2.setAvatar_url(userReceiver.getAvatar_url());
        userReceiver2.setUsername(userReceiver.getUsername());
        userReceiver2.setPassword(userReceiver.getPassword());
    }

    @Override
    public Integer sum(Integer id) {
        return replyDao.sum(id);
    }

    @Override
    public void updateReplyStatus(Integer id) {
        replyDao.updateReplyStatus(id);
    }

}
